//
//  AlertViewController.m
//  Riji
//
//  Created by liujianlong on 2022/8/18.
//

#import "AlertViewController.h"

@interface AlertViewController ()

@end

@implementation AlertViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addNotify];
    [self addtap];
    // Do any additional setup after loading the view.
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    [self.view layoutIfNeeded];
    self.modalPresentationStyle = UIModalPresentationOverFullScreen;
    self.view.backgroundColor = [UIColor colorHex:@"#000000" alpha:0.6];
    return self;
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UIView *view = [self firstResponder:self.view];
    if (view != nil) {
        [super touchesEnded:touches withEvent:event];
        [self.view endEditing:YES];
    }else{
        UITouch *touch = [[touches allObjects] lastObject];
        if ([touch.view isDescendantOfView:self.view.subviews.firstObject] == NO) {
            [self dismissViewControllerAnimated:NO completion:nil];
        }
    }
}


- (void)addtap{
   UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionForTap)];
    tap.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tap];
}
- (void)actionForTap{
    [self.view endEditing:YES];
}



- (void)addNotify{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(methodKeyboardShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(methodKeyboardHidden:) name:UIKeyboardWillHideNotification object:nil];

}
- (void)methodKeyboardShow:(NSNotification*)notifi
{
    NSDictionary *userInfo = [notifi userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGFloat keyboardHeight = [aValue CGRectValue].size.height;
    CGFloat time = [notifi.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGFloat maxY = 0;
    UIView *view = [self firstResponder:self.view];
    if ([view isKindOfClass:NSClassFromString(@"WKContentView")])
    {
        return;
    }
    maxY =  CGRectGetMaxY([view convertRect:view.bounds toView:[[[UIApplication sharedApplication] delegate] window]]);
    CGFloat map = SCREEN_HEIGHT - maxY - keyboardHeight;
    if (map < 0)
    {
        [UIView animateWithDuration:time animations:^{
            self.view.transform = CGAffineTransformMakeTranslation(0, map - 50);
        }];
    }
}
- (void)methodKeyboardHidden:(NSNotification*)notifi
{
    CGFloat time = [notifi.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:time animations:^{
        self.view.transform = CGAffineTransformIdentity;
    }];
}
@end
